
import { defineStore } from 'pinia'


export const useTagsViewStore = defineStore("tagesView", {
  state: () => ({
    topview: [],
    cachedViews:[],
  }),
  actions: {
    setTopview(topview) {
      if (this.topview.some((item) => item.path == topview.path)) return;
      this.addCachedView(topview);
      this.topview.push(
        Object.assign(
          {},
          { ...topview },
          {
            title: topview?.meta?.title || "noname",
          }
        )
      );
    },
    deleteTopview(view) {
      if (this.topview.length === 1) return;
      const curentIndex = this.topview.findIndex(
        (item) => item.path == view.path
      );
      this.topview = this.topview.filter((item) => item.path != view.path);
      this.addCachedView(view);
      let toview;
      if (this.topview.length) {
        if (curentIndex === 0) {
          // 如果删除的是第一个元素，跳转到新数组的第一个元素
          toview = this.topview[0];
        } else if (curentIndex === this.topview.length) {
          // 如果删除的是最后一个元素，跳转到新数组的最后一个元素
          toview = this.topview[this.topview.length - 1];
        } else {
          // 如果删除的是中间元素，跳转到原位置对应的新元素（即前一个元素）
          toview = this.topview[curentIndex - 1];
        }
      }
      if (toview) {
        return toview;
      }
    },
    deleteAllTopview(view) {
      if (this.topview.length === 1) return;
      this.topview = this.topview.filter((item) => item.path == view.path);
      this.addCachedView(view);
      return view?.path;
    },
    addCachedView(view) {
      if (this.cachedViews.includes(view.name)) return;
      if (!view.meta.noCache) {
        this.cachedViews.push(view.name);
      }
    },
  },
});